import re
import os
# import requests
from curl_cffi import requests
import shutil
root = 'static/彼岸图库'
if os.path.exists(root):
    shutil.rmtree(root)

os.mkdir(root)


# 关闭 curl 证书校验（全局一次即可）
os.environ['CURL_CA_BUNDLE'] = ''

url = 'https://pic.netbian.com/4k/index_61.html'


headers = {
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0',

}
# cookies={
#     'PHPSESSID':'ncpop1nur61leskt50r6ehcha6'
# }
response = requests.get(url,headers=headers,impersonate="chrome110",verify=False)
html = response.content.decode('gbk')
# print(html)

items = re.findall(
    r'<li><a href="(/tupian/\d+\.html)".*?<img src="(.*?)".*?alt="(.*?)"',
    html,
    re.DOTALL
)

for item in items:

    # print(item)
    title = item[2]
    # print(title)
    link_ulr = f'https://pic.netbian.com{item[0]}'
    # print(link_ulr)
    img_src_thumb = f'https://pic.netbian.com{item[1]}'
    # print(img_src)

    img_src_clear = requests.get(link_ulr, headers={
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0',
        'cookie':'PHPSESSID=ncpop1nur61leskt50r6ehcha6',

    },impersonate="chrome110",verify=False)
    img_src_clear_content = img_src_clear.content.decode('gbk')
    # img_src_clear_content = img_src_clear.text
    # print(img_src_clear_content)

    # rs = re.findall(r'<div class="photo-pic"><a href="(.*?)" id="img"><img src="(.*?)" data-pic="(.*?)" alt="(.*?)" title="(.*?)"></a></div>',img_src_clear_content,re.DOTALL)
    # for r in rs:
    #     # print(r)
    #     img_src_clear_src = f"https://pic.netbian.com/{r[1]}"
    #     img_src_clear_name = r[3]
    #     # print(img_src_clear_src)
    #     # print(img_src_clear_name)
    #     img_resp = requests.get(img_src_clear_src, headers=headers, timeout=10 ,verify=False)
    #     with open(f'{root}/{img_src_clear_name}','wb') as f:
    #         f.write(img_resp.content)

    rs = re.findall(
        r'<div class="photo-pic"><a href="(.*?)" id="img"><img src="(.*?)" data-pic="(.*?)" alt="(.*?)" title="(.*?)"></a></div>',
        img_src_clear_content,
        re.DOTALL
    )
    for r in rs:
        img_relative = r[1]
        img_url = f'https://pic.netbian.com{img_relative}'
        img_name = f"{r[3]}.jpg"

        # 下载原图二进制
        img_resp = requests.get(img_url, headers={
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36 Edg/141.0.0.0',
            'cookie': 'PHPSESSID=ncpop1nur61leskt50r6ehcha6',
            'Referer':link_ulr,
        }, timeout=10 ,impersonate="chrome110",verify=False)


        # 写入本地
        with open(f'{root}/{img_name}', 'wb') as f:
            f.write(img_resp.content)

        print(f'已保存：{img_name}')

